<template>
    <n-card title="应用信息">
        <template #header-extra>
            <n-button quaternary type="primary" @click="onEdit">编辑</n-button>
        </template>

        <n-spin :show="detailLoading">
            <n-grid x-gap="15" y-gap="15" responsive="screen" cols="1 l:2 xl:4">
                <n-gi>
                    <div class="flex align-mid">
                        <div class="w-30 color-gray">名称</div>
                        <div>{{ detail?.name }}</div>
                    </div>
                </n-gi>
                <n-gi>
                    <div class="flex align-mid">
                        <div class="w-30 color-gray">类型</div>
                        <div>{{ detail?.type }}</div>
                    </div>
                </n-gi>
                <n-gi>
                    <div class="flex align-mid">
                        <div class="w-30 color-gray">备注</div>
                        <div>{{ detail?.remark }}</div>
                    </div>
                </n-gi>
                <n-gi>
                    <div class="flex align-mid">
                        <div class="w-30 color-gray">状态</div>
                        <div>
                            <n-tag
                                size="small"
                                :type="
                                    appStateOptions.find(
                                        (item) => item.value === detail?.state
                                    )?.theme
                                "
                            >
                                {{
                                    appStateOptions.find(
                                        (item) => item.value === detail?.state
                                    )?.label
                                }}
                            </n-tag>
                        </div>
                    </div>
                </n-gi>
                <n-gi>
                    <div class="flex align-mid">
                        <div class="w-30 color-gray">跨域域名</div>
                        <div>
                            {{ detail?.allowed_origin }}
                        </div>
                    </div>
                </n-gi>
                <n-gi>
                    <div class="flex align-mid">
                        <div class="w-30 color-gray">创建时间</div>
                        <div>{{ detail?.create_time }}</div>
                    </div>
                </n-gi>
            </n-grid>
        </n-spin>
    </n-card>
    <AppEdit v-model:show="showEdit" :data="detail" @success="onEditSuccess" />

    <n-card title="应用配置" class="mt-4">
        <template #header-extra>
            <n-space>
                <n-button-group v-if="onConfigEdit && showDesign">
                    <n-button round dashed type="primary" @click="onDesignAdd"
                        >添加字段</n-button
                    >
                    <n-button
                        round
                        dashed
                        type="info"
                        @click="showDesign = false"
                        >保存 / 取消</n-button
                    >
                </n-button-group>

                <n-button-group>
                    <n-button
                        v-if="!showDesign && configEdit"
                        quaternary
                        type="info"
                        @click="onDesign"
                        >表单设计</n-button
                    >
                    <n-button
                        v-if="configEdit"
                        quaternary
                        type="primary"
                        :disabled="showDesign"
                        @click="onConfigSubmit"
                        >保存</n-button
                    >
                    <n-button
                        v-if="configEdit"
                        quaternary
                        :disabled="showDesign"
                        @click="configEdit = false"
                        >取消</n-button
                    >

                    <n-button
                        v-else
                        quaternary
                        type="primary"
                        :disabled="showDesign"
                        @click="onConfigEdit"
                        >编辑</n-button
                    >
                </n-button-group>
            </n-space>
        </template>

        <DesignForm
            v-model:value="configFormState"
            v-model:design="showDesign"
            v-model:layout="designState"
            ref="designFormRef"
            :edit="configEdit"
        />
    </n-card>
</template>

<script setup lang="ts">
import {
    coreAppConfigDetail,
    coreAppConfigUpdate,
    coreAppDetail
} from '@/apis/core/app'
import useState from '@/hooks/useState'
import { ICoreApp, ICoreAppConfig } from '@/types/core/app'
import { useMessage } from 'naive-ui'
import { onMounted, ref, watch } from 'vue'
import AppEdit from './AppEdit.vue'
import { appStateOptions } from '../options'
import { DesignForm } from '@/components/form'
import { useCoreAppStore } from '@/store'

const appStore = useCoreAppStore()

const props = defineProps({
    appId: {
        type: Number,
        required: true
    }
})

const message = useMessage()

/**
 * 详情
 */
const detail = ref<ICoreApp>()
const { state: detailLoading, setState: setDetailLoading } = useState()
function getDetail() {
    setDetailLoading(true)
    coreAppDetail({
        id: props.appId
    })
        .then((res) => {
            detail.value = res
        })
        .catch((e: Error) => message.error(e.message))
        .finally(() => setDetailLoading(false))
}

onMounted(() => {
    getDetail()
    getConfigDetail()
})

/**
 * 编辑
 */
const showEdit = ref(false)
function onEdit() {
    showEdit.value = true
}
function onEditSuccess() {
    getDetail()
}

/**
 * 应用配置
 */
const configDetail = ref<ICoreAppConfig>()
function getConfigDetail() {
    coreAppConfigDetail({
        app_id: props.appId
    })
        .then((res) => {
            configDetail.value = res
        })
        .catch((e: Error) => message.error(e.message))
}

/**
 * 表单设计
 */
watch(
    () => configDetail.value,
    (val) => {
        if (val) {
            designState.value = [...(val.layout || [])]
            configFormState.value = { ...(val.content || {}) }
        }
    },
    { deep: true }
)

const designFormRef = ref()
const showDesign = ref(false)
const designState = ref<ICoreAppConfig['layout']>([])
function onDesignAdd() {
    designFormRef.value?.add()
}
function onDesign() {
    showDesign.value = true
}

/**
 * 编辑应用配置
 */
const configEdit = ref(false)
const configFormState = ref<ICoreAppConfig['content']>({})
function onConfigEdit() {
    configEdit.value = true
}

const configSubmiting = ref(false)
function onConfigSubmit() {
    configSubmiting.value = true
    designFormRef.value
        ?.validate()
        .then(() => {
            return coreAppConfigUpdate({
                app_id: props.appId,
                content: configFormState.value,
                layout: designState.value
            })
        })
        .then(() => {
            message.success('保存成功')
            configEdit.value = false

            if (1000 === props.appId) {
                appStore.getConfig(true)
            }

            getConfigDetail()
        })
        .catch((e: Error) => {
            if (e.message) {
                message.error(e.message)
            }
        })
        .finally(() => (configSubmiting.value = false))
}
</script>
